<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */


namespace app\command;

use app\utils\RedisUtil;
use think\console\Input;
use think\console\Output;
use think\Exception;
use think\facade\Db;

class FileToDatabase extends BaseCommand
{
    protected function configure()
    {
        // 指令配置
        $this->setName('file_to_database')
            ->setDescription('文件数据转入数据库');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->setDb($input, $output);
    }


    protected function visit_save(){
        $data = $this->dirList(writeVisitHistory('',true));
        $data = '['.str_replace('}{','},{',$data).']';
        $data = json_decode($data,true);
        $user_id = array_column($data, 'user_id');
        $agent_id = $insert = $array = [];
        $visit = Db::name('user')
            ->field('id,pid')
            ->where('id', 'IN', $user_id)
            ->select();
        $fission = Db::name('user')
            ->field('id')
            ->where('pid','>',0)
            ->where('pid','not null')
            ->where('create_time','>=',date('Y-m-d H:i:s',time()-86400))
            ->select()
            ->toArray();
        if(empty($fission))
            $fission = [];
        else
            $fission = array_column($fission,'id');
        foreach ($visit AS $key => $value)
            $agent_id[$value['id']] = $value['pid'];
        foreach ($data AS $key => $value) {
            $data[$key]['mall_id'] = $value['mall_id'] ?? 0;
            $data[$key]['is_fission'] = 0;
            $data[$key]['create_time'] = date('Y-m-d H:i:s', $value['create_time']);
            $data[$key]['merchant_id'] = 0;
            $data[$key]['agent_id'] = 0;
            if (!empty($array[$value['user_id']][$value['ip']][$value['url']])) continue;
            if ($value['user_id'] == 0)continue;
            if ($value['mall_id'] == 'null')$data[$key]['mall_id'] = 0;
            if(@in_array($value['user_id'],$fission)) {
                $data[$key]['is_fission'] = 1;
            }
            if (empty($agent_id[$value['user_id']])) {
                $data[$key]['agent_id'] = 0;
            } else {
                $data[$key]['agent_id'] = $agent_id[$value['user_id']];
            }
            $insert[] = $data[$key];
            $array[$value['user_id']][$value['ip']][$value['url']] = 1;
        }
        Db::name('visit')->insertAll($data);
        $this->deldir(writeVisitHistory('',true));
    }

    protected function total_save(){
        $redis = new RedisUtil();
        $info = $redis->get('uvpv_info'.date('Ymd'));
        $data = $redis->get('uvpv_data'.date('Ymd'));
        if (!empty($data)) {
            foreach ($data AS $key => $value) {
                if($key == 'null')continue;
                Db::name('total')
                    ->insert(['uv' => $value['uv'],'pv' => $value['pv'],'mall_id' => $key,'create_time' => date('Y-m-d 00:00:00')]);
            }
        }
        if (!empty($info)) {
            foreach ($info AS $key => $value){
                foreach ($value['details'] AS $index => $item) {
                    $mall_id = $index;
                    if (empty($mall_id)) $mall_id = 0;
                    if ($mall_id == 'null') $mall_id = 0;
                    $insert[] = ['mall_id' => $mall_id,'path' => $item['path'],'create_time' => $item['create_time'],'details' => $item['details']];
                }
            }
            Db::name('uvpv')->insertAll($insert,500);
        }
        $redis->set('uvpv_data',[]);
        $redis->set('uvpv_info',[]);
    }


    protected function dirList($dir_path = '') : string{
        $text = '';
        if(is_dir($dir_path)) {
            $dirs = opendir($dir_path);
            if($dirs) {
                while(($file = readdir($dirs)) !== false) {
                    if($file !== '.' && $file !== '..') {
                        $text .= file_get_contents($dir_path . '/' . $file . '');
                    }
                }
                closedir($dirs);
            }
            return $text;
        } else {
            return '';
        }
    }


    protected function deldir($path){
        //如果是目录则继续
        $files = glob($path.'/*.log');
        foreach ($files as $file) {
            if (is_file($file))unlink($file);
        }
    }

    protected function executeAction(Input $input, Output $output)
    {
        // TODO: Implement executeAction() method.
        try {
            Db::startTrans();
            //$this->visit_save();
            $this->total_save();
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            dd($e->getTraceAsString());
        }
    }
}